package com.duowan.cms.intf.comment3;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.springframework.stereotype.Service;

import com.duowan.cms.common.exception.BaseCheckedException;
import com.duowan.cms.common.util.MD5;
import com.duowan.cms.common.util.NetUtil;
import com.duowan.cms.common.util.PathUtil;
import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.dto.article.ArticleInfo;
import com.duowan.cms.dto.channel.ChannelInfo;
import com.duowan.cms.intf.Constants;

@Service("comment3RemoteService")
public class Comment3ServiceImpl implements Comment3RemoteService {

    /*
     * r :default/domain 访问的方法
    domain :string 站点
    comment_url :string  window.location.pathname获取的值
    c_uniqid :string 当前文章页定义的唯一标识码
    jQueryData :随机 jsonp的callback*/
    @Override
    public Integer getCommentCount(ArticleInfo articleInfo) {
        Map<String, String> paramsMap = new HashMap<String, String>();
        String onlineUrl = articleInfo.getUrlOnLine().trim();
        String domain = articleInfo.getChannelInfo().getDomain();
        String uniqid = new MD5().get(PathUtil.getArticleOnlineUrl(domain, articleInfo.getThreadId())).toLowerCase();
        String comment_url = onlineUrl.substring(domain.length());
        if(!comment_url.startsWith("/")){
            comment_url = "/" + comment_url;
        }
        paramsMap.put("r", "default/domain");
        paramsMap.put("domain", domain.replace("http://", ""));
        paramsMap.put("comment_url", comment_url);
        paramsMap.put("c_uniqid", uniqid);
        
        String responseData = null;
        try {
            responseData = NetUtil.getHttpRequest(paramsMap, Constants.COMMENT3_GETCOMMENT_URL, Constants.EXPIRE_SECONDS);
            return getCommentCountFromJson(responseData);
        } catch (BaseCheckedException e) {
            logger.warn("频道["+articleInfo.getChannelInfo().getId()+"]文章id["+articleInfo.getId()+"]获取评论数失败", e);
            return 0;
        }
    }
    
    private int getCommentCountFromJson(String str) {
        if(StringUtil.isEmpty(str))
            return 0;
        String resultStr = null;
        Pattern p = Pattern.compile("\\{\"total\":\"(\\d+)\"\\}");
        Matcher m = p.matcher(str);
        if(m.find()){
            resultStr = m.group(1);
        }else{
            logger.warn("获取评论数返回的数据：" + str);
        }
        
        return null == resultStr ? 0 : Integer.parseInt(resultStr);
    }
    
    @Override
    public LinkedHashMap<String, String> getMoreCommentCount(String domain, Set<String> uniqids, Integer length) {

        Map<String, String> map = new HashMap<String, String>();
        int i = 0;
        for(String str : uniqids){
            map.put("uniqids["+(i++)+"]", str);
        }
        map.put("limit", length + "");
        String responseData = null;
        String url = Constants.COMMENT3_GETCOMMENT_URL + "?r=default/morecount&domain=" + domain;
        try {
            responseData = NetUtil.postHttpRequest(map, url, Constants.EXPIRE_SECONDS);
            return getResultMap(responseData);
        } catch (Exception e) {
            logger.warn("专区域["+domain+"]获取评论数排行失败,返回数据：" + responseData, e);
            return null;
        } 
    }
    
    private LinkedHashMap<String, String> getResultMap(String responseData) throws Exception{
        
        JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(responseData);
        
        Object o = jsonObject.get("status");
        if(!"201".equals(o.toString())){
            throw new Exception("接口返回描述状态代码：" + o.toString());
        }
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        if(responseData.indexOf("[]") > 0){
            logger.warn("返回评论数据集合为空,可能是uniqid查找不到对应数据!");
            return map ;
        }
        JSONObject rankData = jsonObject.getJSONObject("sums");
        for(Iterator it = rankData.keys(); it.hasNext();){
            Object key = it.next();
            Object value = rankData.get(key);
            //System.out.println(key + ":" + value);
            map.put(key.toString(), value.toString());
        }
        return map;
    }
    
    @Override
    public void openCommentSite(ChannelInfo channelInfo) {
        
        String domain = channelInfo.getDomain().replace("http://", "");
        if(domain.indexOf("/") != -1){
            int index = domain.indexOf("/");
            domain = domain.substring(0, index);
        }
        String name = channelInfo.getName();
        
        Map<String, String> map = new HashMap<String, String>();
        map.put("url", domain);
        map.put("name", name);
        String responseData = null;
        String url = Constants.COMMENT3ADMIN_URL + "?r=domain/interfaceadd";
        //String url = "http://backend.duowan.com/index.php?r=domain/interfaceadd";
        try {
            responseData = NetUtil.postHttpRequest(map, url, Constants.EXPIRE_SECONDS);
            if("201".equals(responseData)){
                logger.info("专区域["+domain+"]开通评论成功!");
            }else{
                logger.info("专区域["+domain+"]开通评论失败，原因：" + getReasonFormResponseData(responseData));
            }
        } catch (Exception e) {
            logger.warn("专区域["+domain+"]开通评论失败,返回数据：" + responseData, e);
        }
    }
    
    private String getReasonFormResponseData(String responseData){
        if("410".equals(responseData)){
            return "410:ip被限";
        }else if("401".equals(responseData)){
            return "401:参数错误";
        }else if("500".equals(responseData)){
            return "500：添加失败";
        }else {
            return "未知：" + responseData;
        }
    }

    public static void main(String[] args) {
        String data = "{\"status\":201,\"sums\":{" +
        "\"e495b3a7d5c9afd67f680d9a61663428\":\"281\"," +
        "\"f3dd424c56fa6577cac2e6958e3a27af\":\"237\"," +
        "\"934dc9785360aa235a93c3378c363e6f\":\"150\"," +
        "\"76f7e02f9bb205277645a36e801f599f\":\"86\"," +
        "\"6b35cbef3c6f3e6cb4fa35c6f5d97e37\":\"57\"," +
        "\"ef93936780b2ff8c003aac5694c5bf7d\":\"55\"," +
        "\"1f1d1ad22bd6e5b17b43ec265806ab19\":\"31\"," +
        "\"4620204c8af9e1131f5905a9bb94ebcd\":\"19\"}}";
        try {
            new Comment3ServiceImpl().getResultMap(data);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

}
